package com.credithc.signature.manager.utils;

import com.alibaba.fastjson.JSONObject;
import com.credithc.signature.common.utils.HttpClientProxy;
import com.credithc.signature.common.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class FileUploadUtil {

    private static String UPLOAD_PATH;

    public static String DOWNLOAD_PATH;

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            log.error("类TemplateMService[inputStreamToFile]方法发生异常", e);
        }
    }

    @Value("${file.upload.url}")
    public void setUploadPath(String uploadPath) {
        UPLOAD_PATH = uploadPath;
    }

    @Value("${file.download.url}")
    public void setDownloadPath(String downloadPath) {
        DOWNLOAD_PATH = downloadPath;
    }

    /**
     * 上传文件
     *
     * @param filePath
     * @param name
     * @return
     * @throws Exception
     */
    public static String upload(String filePath, String type, String name, String requestNo) throws Exception {
        File file = new File(filePath);
        return upload(file, type, name, requestNo);
    }

    /**
     * 上传文件并获取完整地址
     *
     * @param filePath
     * @param name
     * @return
     * @throws Exception
     */
    public static String uploadAndGetUrl(String filePath, String type, String name, String requestNo) throws Exception {
        File file = new File(filePath);
        return DOWNLOAD_PATH + upload(file, type, name, requestNo);
    }

    /**
     * 文件上传
     *
     * @param file
     * @param name
     * @return
     * @throws Exception
     */
    public static String upload(File file, String type, String name, String requestNo) throws Exception {
        String fsId = null;
        CloseableHttpClient httpClient = HttpClientUtils.getHttpClient();
        // 把一个普通参数和文件上传给下面这个地址
            HttpPost httpPost = new HttpPost("http://filesys.hengchang6.com/fs-api/uploadFile.hc");
//        HttpPost httpPost = new HttpPost(UPLOAD_PATH);
        // 把文件转换成流对象FileBody
//            File file = new File(filePath);
        FileBody bin = new FileBody(file);
        //调用者业务ID
        StringBody businessId = new StringBody(requestNo, ContentType.create("text/plain", Consts.UTF_8));
        //调用者系统ID
        StringBody systemId = new StringBody("signature", ContentType.create("text/plain", Consts.UTF_8));
        //文件类型(注* 此处上传pdf类型文件，fileType参数填写为 doc)
        StringBody fileType = new StringBody(type, ContentType.create("text/plain", Consts.UTF_8));
        //文件原始名称
        StringBody fileName = new StringBody(name, ContentType.create("text/plain", Consts.UTF_8));
        //从文件名，非图片类型不需要裁剪 缩放的文件 此参数为空
        StringBody slaveName = new StringBody("", ContentType.create("text/plain", Consts.UTF_8));
        //以浏览器兼容模式运行，防止文件名乱码。
        HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addPart("file", bin)
                .addPart("systemId", systemId)
                .addPart("fileType", fileType)
                .addPart("fileName", fileName)
                .addPart("slaveName", slaveName)
                .addPart("businessId", businessId).setCharset(CharsetUtils.get("UTF-8")).build();

        httpPost.setEntity(reqEntity);

        log.info("发起请求的页面地址 " + httpPost.getRequestLine());
        // 发起请求 并返回请求的响应
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        try {
            log.info("----------------------------------------");
            // 打印响应状态
            log.info(httpResponse.getStatusLine().toString());
            // 获取响应对象
            HttpEntity resEntity = httpResponse.getEntity();
            if (resEntity != null) {
                // 打印响应长度
                log.info("Response content length: " + resEntity.getContentLength());
                // 打印响应内容
                String result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
                JSONObject json = JSONObject.parseObject(result);
                log.info(json.toString());
                Map<String, String> date = null;
                if ("1".equals(json.get("result"))) {
                    date = (Map<String, String>) json.get("data");
                    if ("1".equals(date.get("status"))) {
                        fsId = date.get("fsId");
                    } else {
                        throw new Exception("文件上传文件系统失败:" + date.get("message"));
                    }
                } else {
                    throw new Exception("文件上传文件系统失败:" + json.get("errorMsg").toString());
                }
            }
            // 销毁
            EntityUtils.consume(resEntity);
        } finally {
            httpResponse.close();
        }
        return fsId;
    }

    /**
     * 下载文件--返回文件流
     *
     * @param fsId
     * @return
     */
    public static byte[] downloadImg(String fsId) {
        try {
            if (StringUtils.isNotEmpty(fsId)) {
                return HttpClientProxy.get(DOWNLOAD_PATH, fsId + "&" + "openType=download");
            }
        } catch (IOException e) {
            log.error("下载图片文件发生异常", e);
        }
        return null;
    }

    //测试代码
    public static void main(String[] args) throws Exception {
        HashMap<String, String> map = new HashMap<>(16);
        map.put("fsId", "F12BE4315534402FB6AD733951F0C39B");
        map.put("openType", "download");
        String params = "?fsId=F12BE4315534402FB6AD733951F0C39B&openType=download";
        byte[] bytes = HttpClientProxy.get("http://filesys.hengchang6.com/fs-api/downloadFile.hc", params);
        FileOutputStream out = new FileOutputStream("D://112.png");
        out.write(bytes);
        System.out.println(Arrays.toString(bytes));
    }
}
